package com.sann.spring.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 工具类：和事务管理相关的工具类，它包含了开启事务，提交事务，回滚事务和释放连接
 */
@Component("txManager")
public class TransactionManager {

    @Autowired
    @Qualifier("connectionUtil")
    private ConnectionUtil connectionUtil;

    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            // 关闭自动提交事务，改用手动提交
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放连接,解绑Thread 上的Connection连接
     */
    public void release(){
        try {
            connectionUtil.getThreadConnection().close();//还回连接池中
            connectionUtil.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
